package org.jeecg.modules.system.rule;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import org.jeecg.common.handler.IFillRuleHandler;
import org.jeecg.common.util.CodeUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.manage.entity.SysSerialNumberConfig;
import org.jeecg.modules.manage.service.ISysSerialNumberConfigService;
import org.jeecgframework.core.util.ApplicationContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

/**
 * 编码
 */
public class CodeNumberRule implements IFillRuleHandler {


	@Override
	public Object execute(JSONObject params, JSONObject formData) {
		RedisTemplate redisTemplate=SpringContextUtils.getBean("redisTemplate", RedisTemplate.class);
		String code = ""; // 最终编码
		String codeKey = ""; // 对应编码的Key
		String prefix = "CN"; // 对应编码的前缀,默认 code num 缩写
		int codeSerialNumberLen = 3; // 对应编码流水号长度，默认为3
		String maxCode = ""; // 目前最大编码

		if (params != null) {
			Object obj = params.get("codeKey");
			if (oConvertUtils.isNotEmpty(obj))
				codeKey = obj.toString();
		}

		ISysSerialNumberConfigService sysSerialNumberConfigService = (ISysSerialNumberConfigService) SpringContextUtils
				.getBean("sysSerialNumberConfigServiceImpl");
		LambdaQueryWrapper<SysSerialNumberConfig> query = new LambdaQueryWrapper<SysSerialNumberConfig>()
				.eq(SysSerialNumberConfig::getCodeTag, codeKey);
		SysSerialNumberConfig sysSerialNumberConfigObj = sysSerialNumberConfigService.getOne(query);
		
		// 取自定义前缀
		if (sysSerialNumberConfigObj != null) {
			prefix = sysSerialNumberConfigObj.getCodePrefix();
			codeSerialNumberLen = sysSerialNumberConfigObj.getCodeLength();
		}
        // System.out.println("codeKey:"+codeKey);
		// 获取目前最大编码
         
		Object maxCodeObj = redisTemplate.opsForValue().get(codeKey);

		if (!oConvertUtils.isEmpty(maxCodeObj))
			maxCode = maxCodeObj.toString();

		if (maxCode == null || maxCode == "" || maxCode.equals("")) {
			code = CodeUtil.getNextCode(null,prefix,codeSerialNumberLen);
		} else {

			code = CodeUtil.getNextCode(maxCode,prefix,codeSerialNumberLen);
		}
		
		redisTemplate.opsForValue().set(codeKey, code); //更新redis中的最大编码值

		return code;
	}

}
